package com.hyfrogx.modules.app.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hyfrogx.common.exception.MyException;
import com.hyfrogx.common.utils.QueryExt;
import com.hyfrogx.modules.app.dao.HyInviteInfoDao;
import com.hyfrogx.modules.app.entity.*;
import com.hyfrogx.modules.app.service.*;
import com.hyfrogx.modules.app.utils.FrogxTaskCode;
import com.hyfrogx.modules.manage.entity.coin.CoinDetailEntity;
import com.hyfrogx.modules.manage.entity.task.TaskRewardEntity;
import com.hyfrogx.modules.manage.entity.task.TaskUserInfoEntity;
import com.hyfrogx.modules.manage.service.task.TaskRewardService;
import com.hyfrogx.modules.manage.service.task.TaskUserInfoService;
import com.hyfrogx.modules.manage.util.ScoreCoinUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @version 1.0.0
 * @Author: lfh
 * @Date: 2019/10/23 14:46
 * @Company 汉咏科技
 */
@Service
public class HyInviteInfoServiceImpl extends ServiceImpl<HyInviteInfoDao, HyInviteInfo> implements HyInviteInfoService {

    @Lazy
    @Autowired
    HyAskCodeService hyAskCodeService;

    @Lazy
    @Autowired
    UserService userService;

    @Autowired
    TaskRewardService taskRewardService;

    @Autowired
    TaskUserInfoService taskUserInfoService;

    /**
     * 邀请主要逻辑代码
     * @param inviteInfo
     * @return
     * @throws Exception
     */
    @Override
    public Boolean createInviteInfo(HyInviteInfo inviteInfo){
        // 通过H5传过来的邀请码获取师傅uid,邀请码不会无效因为controller层已做过判断
        //HyAskCode askCode = hyAskCodeDao.getUidByAskCode(inviteInfo.getTaskcode());
        HyAskCode askCode = hyAskCodeService.getAskCodeByCode(inviteInfo.getTaskcode());
        // 查询这个邀请码直接邀请人的所有信息
        User suser = userService.getById(askCode.getUid());
        if (suser == null) {
            throw new MyException("邀请码所有者信息异常");
        }
        inviteInfo.setSphone(suser.getPhone());
        inviteInfo.setSuid(suser.getUid());
        inviteInfo.setSuname(suser.getUsername());
        inviteInfo.setCreated(new Date());
        // 受邀人是不是先注册再受邀请的
        if (inviteInfo.getTuid() != null) {
            User tuser = userService.getById(inviteInfo.getTuid());
            inviteInfo.setTuname(tuser.getUsername());
            inviteInfo.setTphone(tuser.getPhone());
            inviteInfo.setRegisertime(tuser.getCreated());
            inviteInfo.setIsactive(1);
            // 直接受邀的,给受邀人和邀请人各自分配任务积分,否则等注册时候再给两人送积分
            this.addOrder(inviteInfo);
        } else {
            inviteInfo.setIsactive(0);
        }
        return this.save(inviteInfo);
    }


    @Override
    public HyInviteInfo getHyInviteInfoByPhone(String tphone){
        // TODO Auto-generated method stub
        HyInviteInfo hyInviteInfo = this.getOne(new QueryWrapper<HyInviteInfo>().eq("tphone",tphone));
        return hyInviteInfo;
    }


    @Override
    public void addOrder(HyInviteInfo hyInviteInfo){
        // 1.获取邀请好友任务应赠送积分
        List<TaskRewardEntity> list = taskRewardService.findHyTaskRewardByCode(FrogxTaskCode.TaskCode.INVITE);
        if(list.size() <= 0){
            throw new MyException("邀请好友奖励积分配置丢失");
        }
        TaskRewardEntity sUserTaskReward = taskRewardService.getHyTaskReward(list);
        User suser = userService.getById(hyInviteInfo.getSuid());
        // 2.给用户处理积分余额
        userService.addScore(hyInviteInfo.getSuid(), sUserTaskReward.getScore());
        // 3.发送订单到积分中间系统
        CoinDetailEntity coin = new CoinDetailEntity();
        coin.setCoin(Long.valueOf(sUserTaskReward.getScore()));
        coin.setDesc("完成邀请好友任务");
        coin.setMark("邀请好友");
        coin.setNickname(suser.getUsername());
        coin.setTerminal("sever");
        coin.setType("获得");
        try
        {
            // 3.获取该用户token
            String coinToken = ScoreCoinUtils.getToken(suser.getPhone());
            // 4.发送包体至积分项目[userId + channelCode(积分系统通过token直接获取) + CoinDetailEntity]
            ScoreCoinUtils.sendPackage(coin, coinToken);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        // 5.完成任务
        TaskUserInfoEntity hyTaskUserInfo = new TaskUserInfoEntity();
        hyTaskUserInfo.setUid(hyInviteInfo.getSuid());
        hyTaskUserInfo.setRemark("邀请好友" + hyInviteInfo.getTphone());
        hyTaskUserInfo.setTaskId(list.get(0).getTid());
        hyTaskUserInfo.setTaskCode(FrogxTaskCode.TaskCode.INVITE);
        hyTaskUserInfo.setTaskType(FrogxTaskCode.TaskType.SENIOR);
        hyTaskUserInfo.setCommitTime(new Date());
        hyTaskUserInfo.setStatus(FrogxTaskCode.TaskStatus.RECEIVE);
        hyTaskUserInfo.setRewardId(sUserTaskReward.getId());
        hyTaskUserInfo.setRewordScore(sUserTaskReward.getScore());
        taskUserInfoService.UserInfoSave(hyTaskUserInfo);
        // 获取被邀请人应赠送积分
        List<TaskRewardEntity> list2 = taskRewardService.findHyTaskRewardByCode(FrogxTaskCode.TaskCode.BE_INVITE);
        if(list.size() <= 0){
            throw new MyException("填写邀请码奖励积分配置丢失");
        }
        TaskRewardEntity tUserTaskReward = taskRewardService.getHyTaskReward(list2);
        User tuser = userService.getById(hyInviteInfo.getTuid());
        // 5.完成任务
        TaskUserInfoEntity hyTaskUserInfo2 = new TaskUserInfoEntity();
        hyTaskUserInfo2.setUid(hyInviteInfo.getTuid());
        hyTaskUserInfo2.setRemark("填写邀请码,邀请者" + suser.getPhone());
        hyTaskUserInfo2.setTaskId(list2.get(0).getTid());
        hyTaskUserInfo2.setTaskCode(FrogxTaskCode.TaskCode.BE_INVITE);
        hyTaskUserInfo2.setTaskType(FrogxTaskCode.TaskType.NOVICE);
        hyTaskUserInfo2.setRewardId(tUserTaskReward.getId());
        hyTaskUserInfo2.setRewordScore(tUserTaskReward.getScore());
        hyTaskUserInfo2.setStatus(FrogxTaskCode.TaskStatus.FINISH);
        taskUserInfoService.UserInfoSave(hyTaskUserInfo2);
    }

    @Override
    public IPage<HyInviteInfo> getAllInviterByPage(QueryExt queryExt, Map pmap) {
        List<HyInviteInfo> list = this.baseMapper.getAllInviterByPage(queryExt,pmap);
        queryExt.setRecords(list);
        return queryExt;
    }

    @Override
    public HyInviteInfo getHyInviteInfoByTuid(Long tuid){
        // TODO Auto-generated method stub
        HyInviteInfo hyInviteInfo = this.getOne(new QueryWrapper<HyInviteInfo>().eq("tuid",tuid));
        return hyInviteInfo;
    }
    @Override
    public List<HyInviteInfo> getNum(Long userId){
        // TODO Auto-generated method stub
        List<HyInviteInfo> infoList = this.list(new QueryWrapper<HyInviteInfo>().eq("suid",userId));
        // 单独查询每个受邀者去发展的下线数目
        return infoList;
    }
}
